package cn.wolfcode.luowowo.webSite.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.domain.TravelStatisVO;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.domain.TravelComment;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.query.TravelCommentObject;
import cn.wolfcode.luowowo.common.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.webSite.annotation.RequireLogin;
import cn.wolfcode.luowowo.webSite.annotation.UserParam;
import cn.wolfcode.luowowo.webSite.util.CookieUtil;
import cn.wolfcode.luowowo.webSite.util.UMEditorUploader;
import cn.wolfcode.luowowo.webSite.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {

    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IUserInfoRedisService redisService;

    @Reference
    private ITravelCommentService commentService;

    @Reference
    private ITravelStatisRedisService travelStatisService;

    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo")TravelQuery qo,@UserParam UserInfo userInfo){

        model.addAttribute("pageInfo", travelService.query(qo));

        List<TravelComment> list = commentService.listALL();
        model.addAttribute("tcs", list);

        model.addAttribute("log", userInfo);

        return "travel/list";
    }

    @RequestMapping("detail")
    public String detail(Model model, Long id,@UserParam UserInfo userInfo,HttpServletRequest request){

        //查询游记明细
        Travel detail = travelService.get(id);
        TravelContent content = travelService.getContentById(id);  //查询游记内容
        detail.setTravelContent(content);  //把游记内容设置到游记对象里

        //阅读量 +1
        int viewnum = travelStatisService.viewnumIncrease(id,1);

        TravelStatisVO vo = travelStatisService.getTravelStatisVO(id);
        try {
            BeanUtils.copyProperties(detail,vo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        model.addAttribute("detail", detail);

        //关联的目的地
        //调用之前处理吐司的方法,其实就是一层层查询出父地区
        List<Destination> toasts = destinationService.getToasts(detail.getDest().getId());

        //把最后一层给剔除掉
        Destination dest = toasts.remove(toasts.size() - 1);

        model.addAttribute("toasts", toasts);

        //关联当前游记所属目的地下的前三个攻略
        List<StrategyDetail> detailTop3 = strategyDetailService.getDetailTop3(detail.getDest().getId());
        model.addAttribute("sds",detailTop3);

        //关联当前游记所属目的地下的的前三个游记
        List<Travel> ts = travelService.getViewNumTop3(detail.getDest().getId());
        model.addAttribute("ts", ts);

        //展示游记评论list
        TravelCommentObject qo = new TravelCommentObject();

        if(userInfo==null){
            model.addAttribute("isFavor", false);
        }else {
            boolean ret = travelStatisService.isFavor(id, userInfo.getId());
            model.addAttribute("isFavor", !ret);
        }


        qo.setTravelId(id);
        qo.setCurrentPage(1);
        qo.setPageSize(Integer.MAX_VALUE);
        Page page = commentService.query(qo);

        model.addAttribute("list", page.getContent());

        model.addAttribute("bianji",userInfo);

        return "travel/detail";
    }


    @RequestMapping("input")
//    @RequireLogin
    public String input(Model model,Long id){

        if(id!=null){
            Travel travel = travelService.get(id);
            travel.setTravelContent(travelService.getContentById(id));
            model.addAttribute("tv", travel);
        }

        List<Destination> dests = destinationService.getDestByDeep(3);
        model.addAttribute("dests", dests);

        return "travel/input";
    }


    @Value("${file.path}")
    private String filePath;

    //封面处理
    @RequestMapping("/coverImageUpload")
    @ResponseBody  //插件要求必须返回Json
    public Object coverImageUpload(MultipartFile pic) {
        String filename = UploadUtil.upload(pic, filePath);
        return filename;
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo){
        //注入当前用户设置到游记对象里
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);

        return AjaxResult.SUCCESS.addData(id);
    }

    //判断是否已登录,没有的话不能写游记
    @RequestMapping("isLogin")
    @ResponseBody
    public Object isLogin(HttpServletRequest request){
        String token = CookieUtil.getToken(request);

        UserInfo userInfo = redisService.getUserByToken(token);
        if(userInfo==null){
            return AjaxResult.FAIL;
        }
        return AjaxResult.SUCCESS;
    }

    //添加游记评论  添加成功后把评论展示在一个页面模板上返回去拼接在游记页面
    @RequestMapping("commentAdd")
    public String commentAdd(Model model, int floor, TravelComment comment, @UserParam UserInfo userInfo){

        //1.先添加评论数据
        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());

        //c对象表示最新的MongoDB里面评论数据
        TravelComment c = commentService.saveOrUpdate(comment);

        //查询评论数据,添加到模块中

        //新添加的评论
        model.addAttribute("c", c);  //把对象回传过去
        model.addAttribute("floor", floor+1);  //楼层加一

        //增加评论数
        travelStatisService.replynumIncrease(comment.getTravelId(),1);

        return "travel/commentTpl";
    }

    //游记的收藏
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Model model,HttpServletRequest request,Long tid,@UserParam UserInfo userInfo){
        //登录判断
        if(userInfo == null){
            AjaxResult result = new AjaxResult(false,"请先登录");
            result.setCode(102);  //事先约定的未登录状态码
            return result;
        }
        boolean ret = travelStatisService.favornumIncrease(tid,userInfo.getId());

//        model.addAttribute("isFavor",ret);

        return new AjaxResult(ret,"").addData(travelStatisService.getTravelStatisVO(tid));
    }

    //游记的顶
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object travelThumbup(Long tid,@UserParam UserInfo userInfo){
        //登录判断
        if(userInfo == null){
            AjaxResult result = new AjaxResult(false,"请先登录");
            result.setCode(102);  //事先约定的未登录状态码
            return result;
        }
        boolean ret = travelStatisService.thumbsupnumIncrease(tid,userInfo.getId());
        return new AjaxResult(ret,"").addData(travelStatisService.getTravelStatisVO(tid));
    }

}
